package ink.lovejinhu.leetcode;

import org.junit.Test;

import java.util.LinkedList;

/**
 * @author jinhu
 * created 2021-04-26 11:28
 */
public class Solution_0007 {
    @Test
    public void test() {
        int x = 0;
        System.out.println(this.reverse(x));
        x = 123;
        System.out.println(this.reverse(x));
        x = -123;
        System.out.println(this.reverse(x));
        x = 1000000;
        System.out.println(this.reverse(x));
        x = 12340;
        System.out.println(this.reverse(x));
        x = -100000;
        System.out.println(this.reverse(x));
        x = -123400;
        System.out.println(this.reverse(x));
        System.out.println("---------");
        x = Integer.MAX_VALUE;
        System.out.println(this.reverse(x));
        x = Integer.MIN_VALUE;
        System.out.println(this.reverse(x));

        System.out.println(Integer.MAX_VALUE);
        System.out.println(Integer.MIN_VALUE);
    }

    /**
     * 先将元素取出来，然后去除末尾的0
     *
     * @param x
     * @return
     */
    public int reverse(int x) {
        long temp = 0;
        if (x > 0) {
            return this.ifInRange(this.delMod(x));


        } else if (x == 0) {
            return 0;
        } else {
            x = -x;
            return this.ifInRange(-this.delMod(x));
        }

    }

    public long delMod(int x) {
        long result = 0;
        if (x <= 9) {
            return x;
        }
        /**
         * 处理末尾的0
         */
        while (true) {
            if (x % 10 != 0) {
                break;
            }
            x = x / 10;
        }
        LinkedList<Integer> integers = new LinkedList<>();
        while (x > 0) {
            integers.add(x % 10);
            x = x / 10;
        }
        for (Integer temp : integers) {
            result = (result + temp) * 10;
        }
        return result / 10;
    }

    public int ifInRange(long x) {
        if (x > Integer.MAX_VALUE || x < Integer.MIN_VALUE) {
            return 0;
        }
        return (int) x;
    }


    /**
     * 上述代码不美观
     *
     * @param x
     * @return
     */
    public int reverse01(int x) {
        long temp = 0;
        while (x > 0) {
            temp = temp * 10 + x % 10;
            x = x / 10;
        }
        return (temp) == temp ? (int) temp : 0;
    }
}
